<?php
/**
 * Created by PhpStorm.
 * User: von
 * Date: 2017/11/24
 * Time: 14:14
 */
namespace backend\controllers;

use backend\models\MessageUserGroup;
use common\models\InstationMessage;
use common\models\Responses;

class InstationMessageController extends BaseController
{
//    public $freeAccessActions = ['index','get-message'];
    public function behaviors()
    {
        return [
            'ghost-access' => [
                'class' => GhostAccessControl::className(),
            ],
        ];
    }

    public  function actionIndex(){
        $userId = \Yii::$app->user->getId();
        $daiShenPinTiXingData = InstationMessage::getMessage($userId,2,11,0,12);
        $shenPinFanKuiData = InstationMessage::getMessage($userId,2,21,0,22);
        $getMessagePackageData = InstationMessage::getMessage($userId,2,3,1);
        $getMessageProjectData = InstationMessage::getMessage($userId,2,3,2);
        $data = [
            'getMessagePackageData'=>$getMessagePackageData,
            'getMessageProjectData'=>$getMessageProjectData,
            'daiShenPinTiXingData'=>$daiShenPinTiXingData,
            'shenPinFanKuiData'=>$shenPinFanKuiData
        ];
        if (\Yii::$app->request->isAjax){
            if (!empty($daiShenPinTiXingData) && $daiShenPinTiXingData['data']['count']>0) {
                $daiShenPinTiXingCount = $daiShenPinTiXingData['data']['count'];
            }else{
                $daiShenPinTiXingCount = 0;
            }
            if (!empty($shenPinFanKuiData) && $shenPinFanKuiData['data']['count']>0) {
                $shenPinFanKuiCount = $shenPinFanKuiData['data']['count'];
            }else{
                $shenPinFanKuiCount = 0;
            }
            if (!empty($getMessagePackageData) && $getMessagePackageData['data']['count']>0) {
                $getMessagePackageCount = $getMessagePackageData['data']['count'];
            }else{
                $getMessagePackageCount = 0;
            }
            if (!empty($getMessageProjectData) && $getMessageProjectData['data']['count']>0) {
                $getMessageProjectCount = $getMessageProjectData['data']['count'];
            }else{
                $getMessageProjectCount = 0;
            }
            return $daiShenPinTiXingCount+$shenPinFanKuiCount+$getMessageProjectCount+$getMessagePackageCount;
        }else{
            /*
 * 获取提示信息
 * @params :$user_id 用户ID
 *          $group   消息分类  7全部消息
 *          $state   消息状态  true 所有消息
 *          $message 获取消息成功提示信息
 *          $whereType        :0项目 1资产包
 * @return  200
 *          400
            public static function actionGetMessage($user_id,$group = 7,$whereType,$state= 2 , $message = '所有消息'){
 */
            return $this->render('index',$data);
        }
    }
    /*
     *保存消息信息
     *@params:  $group   = int     我的提示中分类
     *          $message = [array] 提示消息，必须格式符合要求
     *          $setstate = 0; 消息状态 默认0 未读，1已阅读
     *          $user_id = [array] 发送给那些用户
     *          $sender_id int 发件人ID
     *          $package_id int 资产包ID
     *          $project_id int 单项目ID
     * @return 成功返回200  错误返回400
     */
    public static  function actionSetmessage($group = 7, $message = [], $setstate= 0 ,$user_id = [],$sender_id=1,$package_id=0,$project_id=0)
    {
        $setGroup   = $group;
        $setMessage = !empty($message)?json_encode($message):[];
        $user_id    = !empty($user_id)?$user_id:[] ;
        $sender_id  = !empty($sender_id)?$sender_id:0;
        $project_id  = !empty($project_id)?$project_id:0;
        $package_id  = !empty($package_id)?$package_id:0;
        switch ($group){
            case  \Yii::$app->params['DAI_SHENPIN']:
                //$message['pack_name'=>资产包名称,'applicant'=>申请人,'application'=>申请事项,'applicationReason'=>申请理由]
                $layout_daishenpi = array_key_exists('pack_name',$message)&&array_key_exists('applicant',$message)&&array_key_exists('application',$message)&&array_key_exists('applicationReason',$message)? 1 : 0 ;
                if ($layout_daishenpi && is_array($user_id)){
                    $user_id = array_unique($user_id);
                    $saveState = \backend\models\InstationMessage::setMessage($setGroup,$setMessage,$setstate,$user_id,$sender_id,$package_id,$project_id);
                    if (!empty($saveState) && $saveState['code']==200){
                        return Responses::response200([],1,'发送成功');
                    }
                    return Responses::response400("消息格式错误");
                }else{
                    return Responses::response400("消息格式错误");
                }
                break;
            case \Yii::$app->params['SHENPIN_FANKUI']:
                //$message['pack_name'=>资产包名称,'application'=>申请事项,'appStatus'=>审批状态,'approver'=>审批人,'appSuggest'=>审批意见]
                $layout_shenpifankui = array_key_exists('pack_name',$message)&&array_key_exists('application',$message)&&array_key_exists('appStatus',$message)&&array_key_exists('approver',$message)&&array_key_exists('appSuggest',$message)? 1 : 0 ;
                if ($layout_shenpifankui && is_array($user_id)){
                    $saveState = \backend\models\InstationMessage::setMessage($setGroup,$setMessage,$setstate,$user_id,$sender_id,$package_id,$project_id);
                    if (!empty($saveState) && $saveState['code']==200){
                        return Responses::response200([],1,'发送成功');
                    }
                }else{
                    return Responses::response400("消息格式错误");
                }
                break;
            case  \Yii::$app->params['GUANZHU_UP']:
                /*
                 * $message
                 * [
                 *  ['pack_name'=>资产包名称,'appStates'=>当前状态,'lastUpdateUser'=>最后一次更新人员]
                 *  ['pack_name'=>资产包名称,'appStates'=>当前状态,'lastUpdateUser'=>最后一次更新人员]
                 * ]
                 */
                $layout_guanzheup = 0;
                foreach ($message as $k => $v) {
                    if (array_key_exists('pack_name',$v)&&array_key_exists('appStates',$v)&&array_key_exists('lastUpdateUser',$v)){
                        $layout_guanzheup++;
                    }else{
                        $layout_guanzheup--;
                    }
                }
                if ($layout_guanzheup && is_array($user_id)){
                    $saveState = \backend\models\InstationMessage::setMessage($setGroup,$setMessage,$setstate,$user_id,$sender_id,$package_id,$project_id);
                    if (!empty($saveState) && $saveState['code']==200){
                        return Responses::response200([],1,'发送成功');
                    }
                }else{
                    return Responses::response400("消息格式错误");
                }
                break;
            default:
                return Responses::response400("传递参数错误");
                break;
        }
    }
    /*
     * 获取提示信息
     * @params :$user_id 用户ID
     *          $group   消息分类  7全部消息
     *          $state   消息状态  true 所有消息
     *          $message 获取消息成功提示信息
     *
     * @return  200
     *          400
     */
    public static function actionGetMessage($user_id,$group = 7,$whereType,$state= 2 , $message = '所有消息'){
        $getMessageData =  InstationMessage::getMessage($user_id,$group,$whereType,$state,$message);
        if (!empty($getMessageData) && $getMessageData['code']==200){
            return $getMessageData;
        }else{
            return Responses::response400('读取数据失败');
        }
    }
    /*
     * 更新信息状态
     * @params :$user_id 需要更新的用户
     *          $state   是否已经更新 1已经更新 0未更新
     *          $message_user_group_id 更新的id
     *
     */
    public static function actionUpmessage($user_id,$state,$message_user_group_id){
        $state = intval($state);
        if (empty($state)){
            $UpMessageState =  InstationMessage::UpMessageState($user_id,$message_user_group_id);
            if (!empty($UpMessageState) && $UpMessageState['code']==200){
                return $UpMessageState;
            }else{
                return Responses::response400('修改数据失败');
            }
        }
    }

    /**
     * 一键读取数据
     */
    public static function actionUpdateAll(){
        $userId = \Yii::$app->user->getId();
        $message_group = \Yii::$app->request->post('message_group',[11,12]);
        $messageGroupModel = MessageUserGroup::find()->where(['=',"user_id",$userId])->andWhere(['in','message_group',$message_group])->asArray()->all();
        if (!empty($messageGroupModel)){
            foreach ($messageGroupModel as $k => $v) {
                $idStrArr[] = $v['id'];
            }
            $whereId = implode(',',$idStrArr);
            $upSql = "UPDATE message_user_group SET message_state = 1 WHERE id in ($whereId)";
            $upNum = \Yii::$app->db->createCommand($upSql)->execute();
            return json_encode(Responses::response200([],$upNum));
        }
        return json_encode(Responses::response200([],0));
    }
}
